/**
 * 高值耗材采购模块，提供医疗服务编辑页面初始化组件功能
 * 
 * @Date: 2016-1-25
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */

define(	["jquery", "sysmanMain", "msgServ", "btnServ","flowInit", "datagridServ",
				"panelUtil", "deptUserSelect", "buttonEvent","supplyEditPage", "uploadfiles","flowHistoric"],
		function($, sysmanMain, msgServ, btnServ,flowInit, datagridServ, panelUtil,
				deptUserSelect, buttonEvent, supplyEditPage,uploadfiles,flowHistoric) {

			'use strict';
			var _typeUrl = '/dictionary/getTree.action', 
			_rootpath, 
			el_width = 300,
			item_code_dic_id = 24,
			el_big_width = 674,  
			window_width = 900, 
			window_height = 700, 
			rootid = 'panel-supply-supplyInquiry', 
			window_id = 'supply-supplyInquiry-win', 
			editIndex = -1
			//业务表单对象
			var supplyInquiryInfoWindow='#win-supply-inquiry-infomation',
			flowHistoricUrl='/flowOperator/flowHistorics.action',	
			supplyInfoUrl='/supplyInquiry/query/getInfoPage.action',
			 _buttonConfig;
			var public_method = {
				
				//点击供应商饼图正在处理事项时弹窗
			pageOpen:function(_options){	
					var _defaultConfig = {
						rootId:'panel-supply-inquiry',
						subSystemCode:'supply',
						moduleCode:'supplyInquiry',						
						initQueryParams:null,
						queryModule:null,
						queryMethod:null,
						width:900,
						height:700
					}
					//获取参数配置信息
					$.extend(_defaultConfig,_options)
					var rootPath = '/'+sysmanMain.getRootPath();
					var _config = sysmanMain.getModuConf('supplyInquiry')
					if(!_config){
						_config = {}
					}
					$.extend(_config,_defaultConfig)
					sysmanMain.setModuConf('supplyInquiry',_config)
					var _param = {
						window:$(supplyInquiryInfoWindow),
						href:rootPath + supplyInfoUrl,
						width:_defaultConfig.width,
						height:_defaultConfig.height,
						initQueryParams:_options,
						onClose:private_method.onClose,
						flag:false}
					datagridServ.windowEdit(_param);	
				},
				
				
				
				//双击查看
				clickRow:function(index,data){
					if(window.console){
						console.info('clicked index: ' + index)
					}
					var $grid = $('#panel-supply-inquiry table.dg-list')
					$($grid).datagrid('clearSelections')
					$($grid).datagrid('selectRow',index)
					var rootPath = '/'+sysmanMain.getRootPath();
					
					_buttonConfig={
						"返回":public_method.changeWindowPanel,
					    "查看详情":public_method.detailWindowInfo
					//	"查看详情":function(){public_method.detailWindowInfo}
						
					}
					var btn = $('#panel-supply-inquiry div.form-panel a.function-btn')
					
					$(btn).unbind('click')
					$(btn).bind('click',public_method.function_btn_listenner)
					
					var $form = '#panel-supply-inquiry div.form-panel form'
					var _selectedRecord = $($grid).datagrid('getSelected')
					$($form).form('load',_selectedRecord)
					
					var $gridHistoric = $('#panel-supply-inquiry div.historics')
					
					flowHistoric.initInternalGrid({historicId:$gridHistoric,record:_selectedRecord})
					public_method.changeWindowPanel()
				},
				
				//双击查看
				clickRow2:function(index,data){
					if(window.console){
						console.info('clicked index: ' + index)
					}
					var $grid = $('#panel-supply-supplyInquiry table.dg-list')
					$($grid).datagrid('clearSelections')
					$($grid).datagrid('selectRow',index)
					var rootPath = '/'+sysmanMain.getRootPath();
					
					_buttonConfig={
					    "查看详情":public_method.detailWindowInfo2				
					}
					var btn = $('#supply-supplyInquiry-win div.edit-panel div.flow-edit-btn')
					
					$(btn).unbind('click')
					$(btn).bind('click',public_method.function_btn_listenner)
					
					var $form = '#supply-supplyInquiry-win div.edit-panel form'
					var _selectedRecord = $($grid).datagrid('getSelected')
					$($form).form('load',_selectedRecord)
					
					var $gridHistoric = $('#supply-supplyInquiry-win div.historics')
					
					flowHistoric.initInternalGrid({historicId:$gridHistoric,record:_selectedRecord})
					public_method.changeWindowPanel()
				},
				// 功能按钮监听函数
				function_btn_listenner : function(e) {
		
					btnServ.applyButton({buttonEvt:e,buttonConfig:_buttonConfig})
		
				},
				//切换
				changeWindowPanel:function(e){
					
					var $listPanel = $('#panel-supply-inquiry div.list-panel' )
					var $formPanel = $('#panel-supply-inquiry div.form-panel' )
					
					public_method.togglePanel({target:$listPanel})
					public_method.togglePanel({target:$formPanel})
					if(e && e.currentTarget){
						$(e.currentTarget).linkbutton('enable');
					}
				},
				//判断是否切换
				togglePanel : function(_options) {
					var _queryParam = {}
					//获取当前模块配置
					var _target
					if(_options && _options.target && _options.target.length>0){
						_target= _options.target
						if(_target.length>0){
							
							var _tmp,isClosed
							var _tmpPanel = $(_target).closest('div.panel')
							isClosed=$(_tmpPanel).attr('style')					
							 
							if(isClosed){
								isClosed = isClosed.toLowerCase();
								_tmp = isClosed.indexOf('display: none')
								if(_tmp<0){
									_target.panel('close')
								}else{
									_target.panel('open')
								}
							}
								
							
						}
					}
				},
				detailWindowInfo:function(e){
						if(window.console){
							console.info('show detail loaded...')
						}
						var _config ={};
						var address=$('#panel-supply-inquiry'),
						 dValue=address.find('input#inquiry_date'),
						value=$(dValue).textbox('getValue'),
						supplyId = address.find('input#supply_id'),
						id=$(supplyId).textbox('getValue');
						
						if(value||id){
							var _param = {id:id,value:value};
							_config.initQueryParams = {condition:_param};
							sysmanMain.setModuConf('supplyDetailInfo',_config)
							
						}						
						supplyEditPage.openPage(_param);
						
						if(e && e.currentTarget){
							$(e.currentTarget).linkbutton('enable');
						}
						/*
						var deptEl;
						if(deptEl.length>0){
							var deptValue = $(deptEl).textbox('getValue');
							var _param = {sqks:deptValue,over_days_ge:50,sxzt:'在办'}
							var initQueryParams = {condition:_param}
							
							
							sysmanMain.setModuConf('dutiesInfo',{initQueryParams:initQueryParams})
							
							sysmanMain.supplyDetail()
						}
						*/
					//	sysmanMain.supplyDetail();
				
			},
				detailWindowInfo2:function(e){
						if(window.console){
							console.info('show detail loaded...')
						}
						var _config ={};
						var address=$('#supply-supplyInquiry-win'),
						 dValue=address.find('input#inquiry_date'),
						value=$(dValue).textbox('getValue'),
						supplyId = address.find('input#supply_id'),
						id=$(supplyId).textbox('getValue');
						
						if(value||id){
							var _param = {id:id,value:value};
							_config.initQueryParams = {condition:_param};
							sysmanMain.setModuConf('supplyDetailInfo',_config)
							
						}
						supplyEditPage.openPage2(_param);
				
			},
			

				/**
				 * 初始化新增页面
				 * 
				 * @param _options.record
				 *            列表选中行
				 * @param _options.form
				 *            页面form对象
				 * @param _options.rootId
				 *            页面根节点id
				 * @param _options.flowStateSelector
				 *            流程状态字段选择器
				 */
				initEdit : function(_options) {

					if (window.console) {
						console.info(' recipel init loaded and startting ...')
					}

					private_method.initFileList();

					var queryUrl = '/' + sysmanMain.getRootPath()
							+ '/supplyInquiry/getListDomain.action';

					var gridParam = {

						height : 100,
						onClickCell : private_method.editCell,
						columns : [[{
									field : 'ck',
									checkbox : "true"
								}, {
									field : 'drug_name',
									title : '药品名称',
									align : 'center',
									halign : 'center',
									width : 60,
									editor : 'text'
								}, {
									field : 'drug_kind',
									title : '药品剂型',
									width : 60,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'format',
									title : '规格',
									width : 60,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'producer',
									title : '生产厂家',
									width : 60,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'amount',
									title : '申请数量 ',
									width : 60,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'replacement',
									title : '有无代替药品',
									width : 60,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}

						]],
						rownumbers : true,
						animate : true,
						striped : true,
						border : true,
						idField : 'id',
						fitColumns : true,
						toolbar : '#' + window_id
								+ ' #inner-table-supplyInquiry'
					};
					if (_options && _options.record && _options.record.id) {
						gridParam.queryParams = {
							mainId : _options.record.id
						};
						gridParam.url = queryUrl;
					}

					var _el = $('#' + window_id + ' #dg-inner-supplyInquiry')
					if (_el.length == 1) {
						_el.datagrid(gridParam)
					}

				},
				
				closeWindow : function() {
					$('#' + rootid + ' a.inner-table-btn').unbind('click');
					$('#' + window_id).empty()
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					_moduleConfig.initParam = {
						editable : true
					};
					sysmanMain.setCurrentModuConfig(_moduleConfig);
				},
				/**
				 * @param _options.rootId
				 * @param _options.conditionSelector
				 * @param _options.
				 */
				initList : function(_options) {
					private_method.initCondition(_options)
				},
				
				//弹出窗口按钮扩展
				buttonExtendPop:function(){
					var _be = public_method.buttonExtends();
					
					return $.extend({},_be,{'查看详情':public_method.detailWindowInfo2})
				}
				,
				/**
				 * @param _options.record
				 */
				buttonExtends : function() {
					var supplyInquiry_inner_table = $('#' + window_id
							+ ' #dg-inner-supplyInquiry')
					return {
						
						'查看详情':public_method.detailWindowInfo,											
						'附件' : function() {
							private_method.uploadInit()
						},
						'返回' : function() {
							console.info("I've got the return button!!!")
							private_method.changePanel({
										classType : 'edit-panel'
									})
							private_method.initFileList();
						},
						'上传' : function() {
							console.info("I've got the upload button!!!")
							private_method.upload()
						},
						'删除' : function() {
							console.info("I've got the upload button!!!")
							private_method.delFile()
						},
						'流程图' : function() {
							private_method.changePanel({
										classType : 'historicalDiagram-panel'
									})
						},
						'流程节点' : function() {
							private_method.changePanel({
										classType : 'historical-panel'
									})
						}
					}
				},

				reCreateField : function(_options) {
					private_method.reCreateField(_options)
				},
				rowDblClick : function(index, row) {
					private_method.rowDblClick(index, row)
				}
				

			}

			var private_method = {
				editCell : function(index, field, value) {
					if (window.console)
						console.info(' editCell fired ...')
					var supplyInquiry_inner_table = $('#' + window_id
							+ ' #dg-inner-supplyInquiry')
					if (editIndex > -1 && (editIndex != index)) {
						$(supplyInquiry_inner_table).datagrid('acceptChanges');
						$(supplyInquiry_inner_table).datagrid('endEdit',
								editIndex);
					}

					$(supplyInquiry_inner_table).datagrid('beginEdit', index);
					editIndex = index
				},
				initFileList : function() {
					var el = $('#' + window_id + ' form.main-form div.fileList')
					var _idEl = $('#' + window_id + ' form.main-form #id')
					var uploadListurl = '/upload/query/getInitListDomain.action'
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					if (!_idEl.val()) {
						return;
					}
					var parm = {
						condition : {
							bizno : _idEl.val(),
							bizcode : _moduleConfig.bizcode
						}
					}
					$.ajax({
								url : '/' + sysmanMain.getRootPath()
										+ uploadListurl,
								type : 'post',
								async : false,
								data : parm,
								success : function(result) {
									var _aParam = {
										target : el,
										data : result
									}

									private_method.appendList(_aParam)
								},
								failure : function(result) {
									if (window.console) {
										console.log('ajax call failured ...')
									}
								}
							})
				},
				appendList : function(_options) {
					if (_options.target && _options.data) {
						$(_options.target).empty();
						var _html = '点击名字下载';
						$.each(_options.data.rows, function(i, e) {
							console.info("got one");
							_html += '<span style = "cursor:pointer" onmouseover="font color="#0000FF"" onmouseout="font color="#FFFFFF"" class = "'
									+ 'fileDownBut'
									+ '"'
									+ 'fileId = "'
									+ e.id
									+ '">' + e.filename + '</span>';
						})
						// private_method.changeStyle()
						$(_options.target).append(_html)
						$(".fileDownBut").unbind('click')
						$(".fileDownBut").bind('click',
								private_method.fileDownload)

					}
				},
				changeStyle : function() {
					$(".fileDownBut").live({
								mouseover : function() {
									$(this).css("font-color", "blue");
								},
								mouseout : function() {
									$(this).css("font-color", "black");
								}
							})
				},

				fileDownload : function(e) {
					if (e) {
						var tpObj = e.currentTarget
						private_method.downloadfile($(tpObj).attr('fileId'));
					}
				},
				downloadfile : function(id) {
					if (window.console) {
						console.log('download file fired ')
					}
					var _url = '/' + sysmanMain.getRootPath()
							+ '/upload/downloadFileTest.action'
					var form = $("<form>");
					form.attr('style', 'display:none');
					form.attr('target', '');
					form.attr('method', 'post');
					form.attr('action', _url);
					var input1 = $("<input>");
					input1.attr('type', 'hidden')
					input1.attr('name', 'id')
					input1.attr('value', id);
					$('body').append(form);
					$(form).append(input1);

					form.submit();
					form.remove();

				},
				uploadInit : function() {
					var _moduleConfig = sysmanMain.getCurrentModuConfig();

					var $edit_window = $('#' + window_id);
					var isSaved = false, _id
					var _idEl = $('#' + window_id + ' form.main-form #id')
					if (_idEl.length == 1) {
						_id = $(_idEl).val()
						if (_id) {
							isSaved = true
						}
					}

					if (!isSaved) {
						msgServ.Msgslide('保存后才能上传附件');
						return
					}
					this.uploadInitList({
								_moduleConfig : _moduleConfig
							});
					private_method.changePanel({
								classType : 'upload-panel'
							})
					if (_moduleConfig.bizcode && _id) {
						this.uploadInitRel({
									_moduleConfig : _moduleConfig
								});
					}
				},

				upload : function() {
					uploadfiles.upload()
				},
				delFile : function() {
					uploadfiles.del({
								biztableid : window_id + ' div.table-archive',
								rootPath : '/' + sysmanMain.getRootPath()
							})
				},
				uploadInitList : function(_options) {
					var _idEl = $('#' + window_id + ' form.main-form #id')
					uploadfiles.initList({
						data : {
							bizno : _idEl.val(),
							bizcode : _options._moduleConfig.bizcode
						},
						rootPath : '/' + sysmanMain.getRootPath(),
						biztableid : window_id
								+ ' div.upload-panel div.table-archive',
						toolbarid : window_id
								+ ' div.upload-panel div.archive-btn a.file_upload_btn'

					})
				},

				uploadInitRel : function(_options) {
					var _idEl = $('#' + window_id + ' form.main-form #id')
					uploadfiles.init({
						data : {
							bizno : _idEl.val(),
							bizcode : _options._moduleConfig.bizcode
						},
						queue_id : window_id
								+ ' div.upload-panel form.upload-form #queue',
						file_id : window_id
								+ ' div.upload-panel form.upload-form #file_upload',
						rootPath : '/' + sysmanMain.getRootPath(),
						rootid : window_id

					})
				},

				changePanel : function(_options) {
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					var tep = $('#' + window_id + ' div.toggle-panel')
					console.info("run, saw?")
					tep.panel('close')
					if (tep.length > 0) {
						tep.panel('close')
						console.info("here all closed")
					}

					// var hd =
					// if(_options && _options.length > 0 && _options.classType
					// && _options.classType.length > 0){
					tep = $('#' + window_id + '  div.' + _options.classType)
					tep.panel('open')
					console.info("here " + _options.classType + " closed")
					// }
				},
				rowDblClick : function(index, row) {

					
					var _param = {
						index:index,
						row:row,
						rootId:rootid,
						editWindow:window_id,
						url:'/supplyInquiry/editPage.action',
						moduleConfig:sysmanMain.getCurrentModuConfig(),
						onClose:public_method.closeWindow
					}				
					buttonEvent.doubleClickEdit(_param);
					
				},
				/**
				 * 初始化条件查询框
				 * 
				 * @param _options.rootId
				 *            窗口根节点id
				 * @param _options.conditionSelector
				 *            条件框节点选择器
				 */
				initCondition : function(_options) {
					if (window.console) {
						console.info('recipel init loaded and starting...')
					}

					flowInit.initList(_options)
				},
				detailInfo : function() {
					if (window.console) {
						console.info('show detail loaded...')
					}

					var _config = {}
					// 查找耗材清单panel
					var innerpanelElement = $('#' + rootid
							+ ' div.inner-table-panel')

					var _inpatientno
					if (innerpanelElement.length > 0) {
						// 判断panel状态
						var isopen = panelUtil.getPanelState({
									target : innerpanelElement
								})
						if (isopen) {
							$(innerpanelElement).panel('close')
						} else {
							$(innerpanelElement).panel('open')
						}
					}

				},
				/**
				 * 更新质询子类信息
				 * 
				 * @param _options.form
				 * @param _options.record
				 * @param _options.target
				 */
				changeSubItem : function(_options) {
					var _subSelect = $(_options.form)
							.find('#inquiry_item_subcode')
					$(_subSelect).combobox({
						textField : 'name',
						valueField : 'id',
						readonly : false,
						url : _rootpath + '/dictionary/getTree.action?id='
								+ _options.record.id,
						onSelect : function(record) {
							var _item = $(_options.form)
									.find('#inquiry_item_sub')
							$(_item).val(record.text)
						}
					})
				},

				reCreateField : function(_options) {

					var normal_width_param = {
						width : el_width
					}
					var big_width_param = $.extend({}, {
								width : el_big_width,
								multiline : true,
								height : 50
							})
					var $form = _options.form
					_rootpath = '/' + sysmanMain.getRootPath()
					var fConfig = {
				bizno:$.extend({fieldType:'textbox'},normal_width_param),		
					inquiry_date:$.extend({fieldType:'datebox'},normal_width_param),		
					//inquiry_item:$.extend({fieldType:'textbox'},normal_width_param),
					supply_name:$.extend({fieldType:'textbox'},normal_width_param),
					inquiry_reason:$.extend({fieldType:'textbox'},big_width_param),
					litigant_content:$.extend({fieldType:'textbox'},big_width_param),
					affirm_name:$.extend({fieldType:'textbox'},normal_width_param),
					affirm_result:$.extend(
						{fieldType:'combobox'},
						{
								textField:'name',
								valueField:'name',
								url:_rootpath + _typeUrl+'?id=' + 112,
								onSelect:function(record){
									var _item = $(_options.form).find('#affirm_result_code')
									$(_item).val(record.id)
									
									var $username = $(_options.form).find('#affirm_name')
									var $userid = $(_options.form).find('#affirm_id')
									
									var curUser = sysmanMain.getCurrentUser()
									$($username).textbox('setValue',curUser.name)
									$($userid).val(curUser.id)
								},
								onLoadSuccess:function(){
									if(selectedRecord && selectedRecord.affirm_result_code){
										$(_confirmSelect).combobox('select',selectedRecord.affirm_result_code)									
									}
								}
						},
						normal_width_param),
					affirm_content:$.extend({fieldType:'textbox'},big_width_param),
					inquiry_item:$.extend(
							{fieldType:'combobox'},
							{
								textField:'name',
								valueField:'name',
								url:_rootpath + _typeUrl+'?id=' + item_code_dic_id,
								onSelect:function(record){
									var _item = $(_options.form).find('#inquiry_item_code')
									$(_item).val(record.id)
									
								}
							},
							normal_width_param),
					litigant_name:$.extend(
						{
							fieldType:'textbox',
							onClickButton:function(data){								
								deptUserSelect.openPage({
									userids:'supply-supplyInquiry-win #litigant_id',
									usernames:'supply-supplyInquiry-win #litigant_name',
									deptid:'supply-supplyInquiry-win #litigant_deptid',
									deptname:'supply-supplyInquiry-win #litigant_deptname'
								})								
							}
						},normal_width_param)

					}
					
					
					
					
					
					flowInit.initField({
								fieldConfig : fConfig,
								fieldStatus : _options.data,
								window_id : window_id
							})
				}

			}

			return public_method;

		})